package com.example.helloworld.listener;

import android.util.Log;
import android.widget.RadioGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.helloworld.R;
import com.example.helloworld.base.BaseFragment;

import java.util.Map;

/**
 * RadioButton切换监听类
 */
public class MyCheckChangeListener implements RadioGroup.OnCheckedChangeListener {

    private static final String TAG = MyCheckChangeListener.class.getSimpleName();

    private FragmentManager fragmentManager;

    private Map<Integer, BaseFragment> baseFragmentMap;

    //上次切换的fragment
    private Fragment latestFragment;

    public MyCheckChangeListener(FragmentManager fragmentManager, Map<Integer, BaseFragment> baseFragmentMap) {
        this.fragmentManager = fragmentManager;
        this.baseFragmentMap = baseFragmentMap;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        //获取选中的fragment
        BaseFragment fragment = baseFragmentMap.get(checkedId);
        //切换fragment
        changeFragment(latestFragment, fragment);
        //更新titleBar的内容
        changeTitleBar();

    }

    private void changeFragment(Fragment fromFragment, Fragment toFragment) {

        if (fromFragment == toFragment) {
            return;
        }

        //保存即将切换的页面实例做为上次切换的fragment
        this.latestFragment = toFragment;
        if (toFragment == null) {
            Log.e(TAG, "toFragment is null");
            return;
        }
        //开启事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (fromFragment != null) {
            //隐藏上个页面
            transaction.hide(fromFragment);
        }
        //判断切换至的页面是否被添加过
        if (toFragment.isAdded()) {
            //显示当前页面
            transaction.show(toFragment);
        } else {
            //添加当前页面
            transaction.add(R.id.fl_content, toFragment);
        }
        //提交事务
        transaction.commit();
    }

    private void changeTitleBar(){
    }
}
